import React, { useEffect, useState } from 'react';
import { Button, List, Avatar, PageHeader, message } from 'antd';
import { fetchProjectList, deleteProject } from '../../api/project';
import eventBus from '../../model/event';
import MyUpload from '../dashboard/upload';
import styled from 'styled-components';
import {timeFormat} from '../../utils/time';
import { Project } from '../../model/project';
import directorySvg from '../../assets/images/directory.svg';
import { useHistory, useRouteMatch } from 'react-router-dom';
import CreateForm from './create';

const ProjectTitle = styled.span`
    cursor: pointer;
    margin-right: 40px;
    &:hover {
        color: #1890ff;
    }
`;

interface Status {
    initLoading: boolean;
    loading?: boolean;
    data: any[];
    list: any[];
}

export default function ProjectList() {
    const [status, setStatus] = useState({
        initLoading: true,
        loading: false,
        data: [],
        list: []
    } as Status);

    const [formVisible, setFormVisible] = useState(false);

    const history = useHistory();
    let { path, url } = useRouteMatch();

    const getData = async (callback: Function) => {
        const response = await fetchProjectList({});
        callback(response);
    }

    function fetchData() {
        getData((res: { data: { data: any[] }; }) => {
            setStatus({
                initLoading: false,
                data: res.data.data,
                list: res.data.data
            });
        });
    }

    const download = (url: string) => {
        window.open(url);
    }

    
    const handleDelete = (project: Project) => {
        deleteProject(project).then(res => {
            if(res.status === 200) {
                message.success('删除成功！');
                fetchData();
            } else {
                message.success('删除失败！');
            }
        });
    }

    const handleView = (project: Project) => {
        history.push(`/dashboard/project/detail?id=${project.id}&name=${project.name}`);
    }

    const loadMore = () => {

    }

    useEffect(() => {
        fetchData();

        eventBus.on('bundle_refresh', () => fetchData());
    }, []);

    return (
        <div>
            <div style={{ marginTop: '20px' }}>
                <PageHeader
                    ghost={false}
                    title="Project"
                    subTitle="project总数: 10"
                    extra={[
                        <Button onClick={() => setFormVisible(true)} key="create">新建项目</Button>  
                    ]}
                >
                </PageHeader>
            </div>
            <CreateForm visible={formVisible} setVisible={setFormVisible} doFetch={fetchData}/>
            <div className="site-layout-background" style={{ padding: 24, minHeight: 380 }}>
                <List
                    className="loadmore-list"
                    loading={status.initLoading}
                    itemLayout="horizontal"
                    dataSource={status.list}
                    renderItem={(item: any) => (
                        <List.Item
                            key={item.id}
                            style={{'cursor': 'pointer'}}
                            actions={[<a key="list-loadmore-delete" onClick={(e) => {handleDelete(item);e.stopPropagation();}}>delete</a>]}
                            onClick={() => handleView(item)}
                        >
                            <List.Item.Meta
                                avatar={
                                    <Avatar src={directorySvg} />
                                }
                                title={<div><ProjectTitle>{item.name}</ProjectTitle><span>{timeFormat(item.ctime)}</span></div>}
                                description={item.description}
                            />
                            <div>上传者: admin</div>
                        </List.Item>
                    )}
                />
            </div>
        </div>
    );
}